using System;
using System.Collections.Generic;
using System.Reflection;
using AjaxPro;
using NExt.Core.Model.Enum;

namespace NExt.Serialization.AjaxPro.Conversion
{
    public class AnonymousObjectJavaScriptConvertor : IJavaScriptConverter
    {
        public AnonymousObjectJavaScriptConvertor()
        {
            m_AllowInheritance = true;
            m_serializableTypes = new Type[] { typeof(global::NExt.Core.Model.Enum.AnonymousObject) };
        }

        public override void Serialize(object objectValue, System.Text.StringBuilder sb)
        {
            sb.Append('{');
            AnonymousObject anonymousObject = (AnonymousObject)objectValue;
            Type objectType = objectValue.GetType();
            SerializeProperties(anonymousObject, true, sb);
            //IEnumerable<FieldInfo> fieldInfos = GetFieldInfos(anonymousObject);

            //b = SerilizationHelper.SerializeVariables(objectValue, sb, fieldInfos);
            //b = SerializeFields(objectValue, sb, b, objectType);
            //b = SerilizationHelper.SerializeProperties(objectValue, sb, b, propertyInfos);
            //b = SerilizationHelper.SerializeExtendedProperties(objectValue, sb, b, objectType);
            //b = SerializeAnonymousConfig(objectValue, sb, b, objectType);

            sb.Append('}');
        }

        private IEnumerable<FieldInfo> GetFieldInfos(AnonymousObject anonymousObject)
        {
            List<FieldInfo> fieldInfoList = new List<FieldInfo>();

            foreach (AnonymousObject currentAnonymousObject in anonymousObject.GetInnerObjects())
            {
                Type type = currentAnonymousObject.GetType();
                FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
                fieldInfoList.AddRange(fieldInfos);
            }
            return fieldInfoList;
        }

        private void SerializeProperties(AnonymousObject anonymousObject, bool isStart, System.Text.StringBuilder sb)
        {
            foreach (AnonymousObject currentAnonymousObject in anonymousObject.GetInnerObjects())
            {
                Type type = currentAnonymousObject.GetType();
                PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                isStart = SerilizationHelper.SerializeProperties(currentAnonymousObject, sb, isStart, propertyInfos);
            }
        }
    }
}